package de.ohmhochschule.bme;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SocketClientActivity extends Activity {

	private EditText editText;
	private TextView textView1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		editText = (EditText) findViewById(R.id.editText1);
		textView1 = (TextView) findViewById(R.id.textView1);

		Button button = (Button) findViewById(R.id.btn_Go);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String sIPandPort = editText.getText().toString();
				String sIP = sIPandPort.substring(0, sIPandPort.indexOf(':'));
				int port = Integer.parseInt(sIPandPort.substring(sIPandPort
						.indexOf(':') + 1));
				Log.i(getLocalClassName(), sIP + ":" + port);

				try {
					Socket client = new Socket(sIP, port);

					// get input and output streams:
					BufferedReader br = new BufferedReader(
							new InputStreamReader(
									client.getInputStream()));
					BufferedOutputStream bos = new BufferedOutputStream(
							client.getOutputStream());

					// write HTTP GET request:
					bos.write("GET /\r\n\r\n".getBytes());
					bos.flush();

					// read incoming data:
					StringBuffer webPage = new StringBuffer();
					String line;
					while (!(null == (line = br.readLine()))) {
						webPage.append(line);
					}

					// close after yourselves:
					br.close();
					client.close();
					bos.close();

					textView1.setText(webPage.toString());

				} catch (IOException e) {
					Log.e(getLocalClassName(), e.getMessage());
				}

			}
		});

	}
}